# -*- coding: utf-8 -*-

import logging
import os
import traceback

import yaml

# 获取当前文件夹的绝对路径
path = os.path.split(os.path.realpath(__file__))[0]
# print(os.getcwd())
# print(os.path.realpath(__file__))
# print(os.path.split(os.path.realpath(__file__)))
# print(path)
# path=os.path.dirname(os.path.abspath(__file__))
# print(path)
projectname = 'zwx009'
# print(len(projectname))
# idx = path.find(projectname)
# print(idx)
# path = path[:idx + len(projectname)]
# print(path)
# 处理是不是主入口运行
if path.endswith(projectname):
    pass
else:
    # 返回Projectname所在位置的下标
    idx = path.find(projectname)
    # print(idx)
    # 截取到项目的根目录：F:\python\Test_009
    path = path[:idx + len(projectname)]
    # print(path)

# 读取配置文件
with open(file=path + "/lib/conf.yaml", mode='r', encoding="utf-8") as file:
    # yaml.load()返回的字典数据
    # logging_yaml1 = yaml.load(stream=file, Loader=yaml.FullLoader)
    # print(logging_yaml1)
    # print(file)
    # 获取yaml里面的配置信息
    logging_yaml = yaml.load(stream=file, Loader=yaml.FullLoader).get('logger')
    # 添加日志文件的存放位置到字典里
    logging_yaml['filename'] = path + logging_yaml.get('filename')
    # 创建FileHandler对象，将日志保存到log.log中
    handler = [logging.FileHandler(filename=logging_yaml['filename'], encoding="utf-8")]
    # 从logging_yaml移除filename，filemode
    logging_yaml.pop('filename')
    logging_yaml.pop('filemode')
    # 配置logging日志：主要从文件中读取handler的配置、formatter（格式化日志样式）、logger记录器的配置
    logging.basicConfig(handlers=handler, **logging_yaml)
    # logging.basicConfig(**logging_yaml,filename='123log.txt')

# 获取根记录器：配置信息从yaml文件中获取，只会输出到日志文件
logger = logging.getLogger()
# 创建输出到控制台的输出流
console = logging.StreamHandler()
# 设置日志等级
console.setLevel(logging_yaml['level'])
# 设置日志格式
console.setFormatter(logging.Formatter(logging_yaml['format']))
# 将logger添加到控制台输出
logger.addHandler(console)

if __name__ == "__main__":
    # 等级顺序
    logger.debug("DEBUG")
    logger.info("INFO")
    logger.warning('WARNING')
    logger.error('ERROR')
    # 也可以打印异常报错信息
    try:
        int('a')
    except Exception as e:
        logger.error(e)
        logger.error(traceback.format_exc())

    # print(type((1, 2)) == tuple)
